var git = require('../libs/git');

module.exports = {
    startTask: startTask,
    stopTask:  stopTask,
    getList:   getList,
    getState:  getState
}

var g_State = "idle",      // 任务状态 "idle", "busy", "error"
    g_TaskError,           // 任务错误信息
    g_TaskCurrent,         // 任务进度
    g_TaskTotal,           // 任务总数
    g_ForceStopTask,       // 强制中断任务执行
    g_Project,             // 当前Git项目
    g_Branch,              // 当前Git分支
    g_LocalDir,
    g_RemoteDir;

// 任务流程
function start() {
    g_State = "busy";
    
    // 检查是否有更新
    if( !git.pull( g_LocalDir ) ) {
        g_State = "error";
        g_TaskError = "不需要更新!";
        return;
    }
    
    // 从服务器获取提交次数
    
}

function startTask( req, res, next ) {
    res.status(200).json( { sucess: true } );
}

function stopTask( req, res, next ) {
    
    g_Project = req.project.value;
    g_Branch = req.branch.value;
    
    if( g_State != "idle" ) {
        res.status(406).json( { success: false } );
        return;
    } else {
        res.status(200).json( { success: true } );
    }
}

function getList( req, res, next ) {
    res.status(200).json( { data: null } );
}

function getState( req, res, next ) {
    switch ( g_State ) {
        case "idle":
            res.status(200).json( { state: g_State } );
            break;
        
        case "busy":
            res.statue(200).json({ 
                state: g_State,
                current: g_TaskCurrent,
                total: g_TaskTotal
            });
            
        case "error":
            res.status(406).json({
                state: g_State,
                info: g_TaskError
            });
    
        default:
            break;
    }
}

